/**
 *
 * 自定义路由方法，
 * 弃用默认的路由跳转方法，以方便对路由进行修改
 *
 * */

import 'package:demo_flutter/library.dart';
// pages
import 'package:demo_flutter/pages/index_page/page.dart';
import 'package:demo_flutter/pages/ad_page/page.dart';
import 'package:demo_flutter/pages/main_page/page.dart';
import 'package:demo_flutter/pages/sliver_test_page/page.dart';

// store
import 'package:demo_flutter/store/global_store/state.dart';
import 'package:demo_flutter/store/global_store/store.dart';

// middleware
import 'package:demo_flutter/middleware/lifecycle.dart';





final Map<String, Page<Object, dynamic>> _pages = {
  /// app 主页
  'main_page': MainPage(),

  /// app启动页面
  'index_page': IndexPage(),

  /// 广告页面，可以用来加载前置资源
  'ad_page': ADPage(),

  /// sliver 家族尝试学习
  'sliver_test_page': SliverTestPage()
};



void _visitor(String path, Page<Object, dynamic> page){
  /// 只有特定的范围的 Page 才需要建立和 AppStore 的连接关系
  /// 满足 Page<T> ，T 是 GlobalBaseState 的子类
  if (page.isTypeof<GlobalBaseState>()) {
    /// 建立 AppStore 驱动 PageStore 的单向数据连接
    /// 1. 参数1 AppStore
    /// 2. 参数2 当 AppStore.state 变化时, PageStore.state 该如何变化
    page.connectExtraStore<GlobalState>(GlobalStore.store,
            (Object pagestate, GlobalState appState) {
          final GlobalBaseState p = pagestate;
          if (p.themeColor != appState.themeColor) {
            if (pagestate is Cloneable) {
              final Object copy = pagestate.clone();
              final GlobalBaseState newState = copy;
              newState.themeColor = appState.themeColor;
              return newState;
            }
          }
          return pagestate;
        });
  }

  /// AOP
  /// 页面可以有一些私有的 AOP 的增强， 但往往会有一些 AOP 是整个应用下，所有页面都会有的。
  /// 这些公共的通用 AOP ，通过遍历路由页面的形式统一加入。
  page.enhancer.append(
    /// View AOP
    viewMiddleware: <ViewMiddleware<dynamic>>[
      safetyView<dynamic>(),
    ],

    /// Adapter AOP
    adapterMiddleware: <AdapterMiddleware<dynamic>>[
      safetyAdapter<dynamic>()
    ],

    /// Effect AOP
    effectMiddleware: <EffectMiddleware<dynamic>>[
      pageAnalyticsMiddleware<dynamic>(),
    ],

    /// Store AOP
    middleware: <Middleware<dynamic>>[
      logMiddleware<dynamic>(tag: page.runtimeType.toString()),
    ],
  );
}

final AbstractRoutes routes = new PageRoutes(
  pages: _pages,
  visitor: _visitor,
);